var azure = require('azure');
var qs = require('querystring');

exports.get = function(request, response) {
    // Use "request.service" to access features of your mobile service, e.g.:

    console.log("azure library loaded");

    // Get user id from request
    var storageName = '<Your Storage Name>';
    var host = storageName + '.blob.core.windows.net';    
    var storageKey = '<Your Storage Key>';    

    // get blob service
    var sasService = azure.createBlobService(storageName, storageKey, host);
    
    var containerName = request.query.containername;
    
    // does the container exist, if not then create
    try {
        sasService.createContainerIfNotExists(containerName, function(error){
            if (!error) {
                // if not errored then continue
                // return read/write access for next 30 mins
                
                var sharedAccessPolicy = {
                        AccessPolicy: {
                            Permissions: "rwdl",
                            Expiry: formatDate(new Date(new Date().getTime() + 30 * 60 * 1000))
                        }
                };
                        
                var sasKey = getSAS(storageName, storageKey, '/' + containerName, 
                    azure.Constants.BlobConstants.ResourceTypes.CONTAINER, sharedAccessPolicy);
            
                // extract body of message and store as file
                response.send(statusCodes.OK, { sasKey : sasKey, storageUrl : 'http://' + host });
            }
        });
    }
    catch (err) {
        console.log(err + "hello");
        response.send(400, { error: err.toString() });
    }    
};

function getSAS(storageName, storageKey, path, resourceType, sharedAccessPolicy) { 
    console.log("called getSAS");
     return qs.encode(new azure.SharedAccessSignature(storageName, storageKey)
           .generateSignedQueryString(path, {}, resourceType, sharedAccessPolicy)); 
}

function formatDate(date){ 
        var raw = date.toJSON();
        //blob service does not like milliseconds on the end of the time so strip
        return raw.substr(0, raw.lastIndexOf('.')) + 'Z'; 
}